package common.fengkai.filepost.JVM;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.net.URLDecoder;
import java.util.Map;

/**
 * @author Fengkai
 * @creat 2021/12/16
 */
@Slf4j
public class WatchDog implements  Runnable{


    private Map<String, FileDefine> fileDefineMap;

    public WatchDog(Map<String, FileDefine> fileDefineMap) {
        this.fileDefineMap = fileDefineMap;
    }

    @SneakyThrows
    @Override
    public void run () {
        String path = this.getClass().getResource("").getPath();
        String decode = URLDecoder.decode(path, "utf-8");
        File file = new File(decode);
        File[] files = file.listFiles();
        for (File watchFile : files) {
            long newTime = watchFile.lastModified();
            FileDefine fileDefine = fileDefineMap.get(watchFile.getPath());
            long oldTime = fileDefine.getLastDefine();
            if (oldTime != newTime){
                log.info("文件被修改,热加载中-----------");
                fileDefine.setLastDefine(newTime);
                //重新触发加载类
                loadMyClass(watchFile.getName());
            }
        }
    }

    private void loadMyClass(String className) {
        try {
            MyClassLoader myClassLoader = new MyClassLoader();
            myClassLoader.findClass(className.replace(".class", ""), true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
